package cn.com.taiji.oospub.wechat.controller.member;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.HisAddressUtil;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.Signature;
import cn.com.taiji.oospub.wechat.controller.BaseLogController;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.entity.ReceiveAddress;
import cn.com.taiji.oospub.wechat.service.IAccesstokensaveService;
import cn.com.taiji.oospub.wechat.service.IMemberBaseInfoService;
import cn.com.taiji.oospub.wechat.service.IReceiveAddressService;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.com.taiji.oospub.wechat.scheduler.AccessTokenScheduler.jsapi_ticket;

@Controller
@RequestMapping("/wx/address")
public class AddressController extends BaseLogController {
    @Value("${appID}")
    private String appId;
    @Value("${childrenSpace}")
    private String childrenSpace;
    @Value("${his_address_url}")
    private String hisAddressUrl;
    @Autowired
    private IReceiveAddressService receiveAddressService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IAccesstokensaveService accesstokensaveService;
    @Autowired
    private Signature signature;
    @Autowired
    private HisAddressUtil hisAddressUtil;

    /**
     * 获取配送地址
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/getReceiveAddress", method = RequestMethod.POST)
    @ResponseBody
    public String getReceiveAddress(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        QueryWrapper<ReceiveAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Member_Id", member.getId());
        queryWrapper.eq("is_delete", "0");
        if (StringUtils.hasText(id)) {
            queryWrapper.eq("id", id);
            member.setReceiveAddress(id);
        }
        queryWrapper.orderByDesc("Is_First");
        List<ReceiveAddress> receiveAddressList = receiveAddressService.list(queryWrapper);
        for (ReceiveAddress receiveAddress : receiveAddressList) {
            receiveAddress.setAddressDetail(receiveAddress.getAddress());
            if ("1".equals(receiveAddress.getIsFirst())) {
                receiveAddress.setIsDefault(true);
            } else {
                receiveAddress.setIsDefault(false);
            }
        }
        if (StringUtils.isEmpty(member.getReceiveAddress())) {
            if (receiveAddressList.size() > 0) {
                member.setReceiveAddress(receiveAddressList.get(0).getId());
            }
        }
        WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, member);
        model.addAttribute("AddressList", receiveAddressList);
        model.addAttribute("defaultAddress", receiveAddressService.getById("admin"));
        model.addAttribute("member", member);
        return JSONObject.toJSONString(model);
    }

    /**
     * 添加配送地址
     */
    @RequestMapping(value = "/addressAdd", method = RequestMethod.POST)
    public void addressAddPost(@RequestBody ReceiveAddress receiveAddress, HttpServletRequest request, HttpServletResponse response) throws IOException {

        try {
            MemberBaseInfo memInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
            receiveAddress.setName(receiveAddress.getName().trim());
            receiveAddress.setMemberId(memInfo.getId());
            receiveAddress.setCreateTime(LocalDateTime.now());
            receiveAddress.setAddress(receiveAddress.getAddressDetail());
            if (receiveAddress.isIsDefault()) {
                QueryWrapper<ReceiveAddress> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("Is_First", "1");
                queryWrapper.eq("Member_Id", memInfo.getId());
                queryWrapper.eq("is_delete", "0");
                ReceiveAddress addressServiceOne = receiveAddressService.getOne(queryWrapper, false);
                if (addressServiceOne != null) {
                    addressServiceOne.setIsFirst("0");
                    receiveAddressService.updateById(addressServiceOne);
                }
                receiveAddress.setIsFirst("1");
            } else {
                receiveAddress.setIsFirst("0");
            }
            if (StringUtils.isEmpty(memInfo.getPatientNumber()) && StringUtils.hasText(hisAddressUrl)) {
                if (StringUtils.hasText(receiveAddress.getHisSpaceID()) && !StringUtils.hasText(receiveAddress.getPatientNumber())) {
                    memInfo.setPatientNumber(hisAddressUtil.getHospitalNumberByHisSpaceId(receiveAddress.getHisSpaceID()));
                    memberBaseInfoService.updateById(memInfo);
                } else if (StringUtils.hasText(receiveAddress.getPatientNumber())) {
                    memInfo.setPatientNumber(receiveAddress.getPatientNumber());
                    memberBaseInfoService.updateById(memInfo);
                }
            }
            receiveAddressService.save(receiveAddress);
            memInfo.setReceiveAddress(receiveAddress.getId());
            WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, memInfo);
            writeSuccessToBrowers("添加地址成功", response);
        } catch (Exception e) {
            writeFailToBrowers(e.getMessage(), response);
        }
    }

    /**
     * 修改配送地址
     */

    @RequestMapping(value = "/updataAddress", method = RequestMethod.POST)
    public void addressDetailSavePost(@RequestBody ReceiveAddress receiveAddress, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            MemberBaseInfo memInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
            System.out.println("##########################updataAddressupdataAddressupdataAddressupdataAddressS" + receiveAddress.getAddress());
            ReceiveAddress oldAddress = receiveAddressService.getById(receiveAddress.getId());
            if (receiveAddress.isIsDefault()) {
                QueryWrapper<ReceiveAddress> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("Is_First", "1");
                queryWrapper.eq("Member_Id", memInfo.getId());
                queryWrapper.eq("is_delete", "0");
                ReceiveAddress addressServiceOne = receiveAddressService.getOne(queryWrapper, false);
                if (addressServiceOne != null) {
                    addressServiceOne.setIsFirst("0");
                    receiveAddressService.updateById(addressServiceOne);
                }
                receiveAddress.setIsFirst("1");
            } else {
                receiveAddress.setIsFirst("0");
            }
            if (StringUtils.isEmpty(receiveAddress.getAddress()) || StringUtils.isEmpty(receiveAddress.getArchitecture())) {
                receiveAddress.setArchitecture(oldAddress.getArchitecture());
                receiveAddress.setAddress(oldAddress.getAddress());
            }
            receiveAddress.setName(receiveAddress.getName().trim());
            if (StringUtils.isEmpty(memInfo.getPatientNumber()) && StringUtils.hasText(hisAddressUrl)) {
                if (StringUtils.hasText(receiveAddress.getHisSpaceID()) && !StringUtils.hasText(receiveAddress.getPatientNumber())) {
                    memInfo.setPatientNumber(hisAddressUtil.getHospitalNumberByHisSpaceId(receiveAddress.getHisSpaceID()));
                    memberBaseInfoService.updateById(memInfo);
                } else if (StringUtils.hasText(receiveAddress.getPatientNumber())) {
                    memInfo.setPatientNumber(receiveAddress.getPatientNumber());
                    memberBaseInfoService.updateById(memInfo);
                }
            }
            if (receiveAddressService.updateById(receiveAddress)) {
                memInfo.setReceiveAddress(receiveAddress.getId());
                WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, memInfo);
                writeSuccessToBrowers("修改地址成功", response);
            } else {
                writeFailToBrowers("修改地址失败", response);
            }
        } catch (Exception e) {

            writeFailToBrowers(e.getMessage(), response);
        }
    }

    /**
     * 删除配送地址
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public void delPost(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
            ReceiveAddress receiveAddress = receiveAddressService.getById(id);
            System.out.println("##########################3" + receiveAddress.getAddress());
            receiveAddress.setIsDelete(true);
            receiveAddressService.updateById(receiveAddress);
            String addressId = member.getReceiveAddress();
            if (id.equals(addressId)) {
                QueryWrapper<ReceiveAddress> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("Member_Id", member.getId());
                queryWrapper.eq("is_delete", false);
                queryWrapper.orderByDesc("Is_First");
                ReceiveAddress selected = receiveAddressService.getOne(queryWrapper, false);
                if (selected != null) {
                    member.setReceiveAddress(selected.getId());
                } else {
                    member.setReceiveAddress(null);
                }
            }
            WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, member);
            writeSuccessToBrowers("删除成功", response);
        } catch (Exception e) {
            writeFailToBrowers(e.getMessage(), response);
        }
    }


    @RequestMapping("/getChildrenSpace")
    @ResponseBody
    public String getChildrenSpace(@RequestParam(value = "spaceCode", defaultValue = "") String spaceCode) {
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("spaceCode", spaceCode);
        String result = restTemplate.postForObject(childrenSpace, paramMap, String.class);
        List<JSONObject> resultList = JSONObject.parseArray(result, JSONObject.class);
        resultList = resultList.stream().filter(i -> "1".equals(i.getString("active"))).collect(Collectors.toList());
        return JSONObject.toJSONString(resultList, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/searchSpaceInfo")
    @ResponseBody
    public String searchSpaceInfo(@RequestParam(value = "code", defaultValue = "") String code, Model model, HttpServletRequest request) throws UnsupportedEncodingException {

        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        if (member != null) {
            model.addAttribute("name", member.getName());
            model.addAttribute("tel", member.getMobile());
        }
        model = hisAddressUtil.searchSpaceInfo(code, model);



            return JSONObject.toJSONString(model);
    }

    @GetMapping("/getScanQRSign")
    @ResponseBody
    public String getScanQRSign(@RequestParam(value = "url") String url) throws UnsupportedEncodingException {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("timestamp", System.currentTimeMillis() / 1000);
        paramMap.put("noncestr", IdUtil.simpleUUID());
        paramMap.put("url", url);
        paramMap.put("jsapi_ticket", jsapi_ticket);
        String sign = signature.getSignNokey(paramMap);
        paramMap.put("appId", appId);
        paramMap.put("signature", sign);
        return JSONObject.toJSONString(paramMap);
    }

    @GetMapping("/getCabinetAddress")
    @ResponseBody
    public String getCabinetAddress() {
        List<ReceiveAddress> receiveAddressList = receiveAddressService.query().eq("is_delete", "0")
                .eq("Member_Id", "admin").list();
        return JSONObject.toJSONString(receiveAddressList);
    }

}
